package ink;

import java.beans.ConstructorProperties;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ***********************************************************
 * Copyright  2019 八维通科技有限公司 Inc.All rights reserved.  *
 * ***********************************************************
 * <p>
 * description:
 *
 * @author zjf
 * @date 2020-11-10 20:31:15
 */
public class DateFormatUtil {
    private static final ConcurrentHashMap<String, ThreadLocal<SimpleDateFormat>> map = new ConcurrentHashMap();

    public DateFormatUtil() {
    }

    public static SimpleDateFormat getSimpleDateFormat(final String pattern) {
        if (pattern != null && !pattern.isEmpty()) {
            ThreadLocal<SimpleDateFormat> threadLocal = (ThreadLocal)map.get(pattern);
            if (threadLocal == null) {
                threadLocal = new ThreadLocal<SimpleDateFormat>() {
                    protected SimpleDateFormat initialValue() {
                        return new SimpleDateFormat(pattern);
                    }
                };
                threadLocal = (ThreadLocal)map.putIfAbsent(pattern, threadLocal);
                if (threadLocal == null) {
                    threadLocal = (ThreadLocal)map.get(pattern);
                }
            }

            return (SimpleDateFormat)threadLocal.get();
        } else {
            throw new IllegalArgumentException(String.format("illegal param: %s", pattern));
        }
    }

    public static void main(String[] args) {
        SimpleDateFormat sdf = getSimpleDateFormat(DateFormatUtil.EFormatPattern.yyyy_MM_dd_HH_mm_ss.getValue());
        System.out.println(sdf.format(new Date()));
        System.err.println(sdf.format(new Timestamp((new Date()).getTime())));
        SimpleDateFormat sdf2 = new SimpleDateFormat(",.,.这都可以");
        System.out.println(sdf2.format(new Date()));
    }

    public static enum EFormatPattern {
        yyyy_MM_dd_HH_mm_ss_SSS("yyyy-MM-dd HH:mm:ss.SSS"),
        yyyy_MM_dd_HH_mm_ss("yyyy-MM-dd HH:mm:ss"),
        yyyy_MM_dd_HH_mm("yyyy-MM-dd HH:mm"),
        yyyyMMddHHmmss("yyyyMMddHHmmss"),
        HH_mm_ss("HH:mm:ss"),
        HH_mm("HH:mm"),
        HH("HH"),
        yyyy_MM("yyyy-MM"),
        yyyy_MM_dd("yyyy-MM-dd"),
        MM_dd("MM-dd"),
        yyyy_sprit_MM_sprit_dd("yyyy/MM/dd"),
        yyyy_sprit_MM_sprit_dd_HH_mm_ss("yyyy/MM/dd/HH:mm:ss"),
        yyyyMMdd("yyyyMMdd");

        String value;

        @ConstructorProperties({"value"})
        private EFormatPattern(String value) {
            this.value = value;
        }

        public String getValue() {
            return this.value;
        }
    }
}
